<?php
/**
 * Build the pagination from the input infos
 * @param int $totalResult Total number of results
 * @param int $currentPage Current Page
 * @param int $maxResultPerPage Max result per page
 * @param int $maxPagePerSegment Max page per segment
 */
function paginationBuildPagination($totalResult, $currentPage, $maxResultPerPage, $maxPagePerSegment) {
  #caculate the pagination infos
  $totalPage = ceil($totalResult/$maxResultPerPage);
  $totalSegment = ceil($totalPage/$maxPagePerSegment);
  $currentSegment = ceil($currentPage/$maxPagePerSegment);
  $isLastPage = ($currentPage == $totalPage);
  $isFirstPage = ($currentPage == 1);
  $isLastSegment = ($currentSegment == $totalSegment);
  $isFirstSegment = ($currentSegment == 1);
  $currentBeginPage = ($currentSegment-1)*$maxPagePerSegment + 1;
  $currentEndPage = (!$isLastSegment) ? $currentSegment*$maxPagePerSegment : $totalPage;

  #build page url
  $requestQueryWithoutPage = preg_replace('/(\&?p=[0-9]*)?/', '', $GLOBALS['request_query']);
  $separationSign = (empty($requestQueryWithoutPage)) ? '' : '&';
  
  $uriSelfWithoutPage = $GLOBALS['uri_self'].'?'.$requestQueryWithoutPage.$separationSign;
  
  #build label
  $label = "<div class='label'>Trang ".$currentPage."/".$totalPage."</div>";
  
  #build prev seg and prev page buttons
  $prevSeg = "<div class='prev-seg'><a href='".$uriSelfWithoutPage."p=".($currentBeginPage-$maxPagePerSegment)."'><<</a></div>";
  $prevPage = "<div class='prev-page'><a href='".$uriSelfWithoutPage."p=".($currentPage-1)."'><</a></div>";
  
  #build page list
  $pages = '';
  for($page = $currentBeginPage; $page <= $currentEndPage; $page++) {
    $pages .= ($page==$currentPage) ? "<div class='page current'>" : "<div class='page'>";
    $pages .= ($page!=$currentPage) ? "<a href='".$uriSelfWithoutPage."p=".$page."'>".$page."</a>" : $page;
    $pages .= "</div>";
  }
  
  #build next page and next seg buttons
  $nextPage = "<div class='next-page'><a href='".$uriSelfWithoutPage."p=".($currentPage+1)."'>></a></div>";
  $nextSeg = "<div class='next-seg'><a href='".$uriSelfWithoutPage."p=".($currentBeginPage+$maxPagePerSegment)."'>>></a></div>";

  #build total result
  $total = "<div class='total-result'>Tìm thấy <b>".$totalResult."</b> kết quả</div>";
  
  #build pagination
  $pagination  = "<div class='pagination'>";
  $pagination .= $label;
  $pagination .= (!$isFirstSegment) ? $prevSeg : '';
  $pagination .= (!$isFirstPage) ? $prevPage : '';
  $pagination .= $pages;
  $pagination .= (!$isLastPage) ? $nextPage : '';
  $pagination .= (!$isLastSegment) ? $nextSeg : '';
  $pagination .= $total;
  $pagination .= "</div>";
  return $pagination;
}